package main

import (
	"context"
	"fmt"
	"os/exec"
	"time"
)

func main() {
	var (
		ctx     context.Context
		cancelF context.CancelFunc
		flag    chan int
	)

	flag = make(chan int)
	ctx, cancelF = context.WithCancel(context.Background())

	go func(cctx context.Context) {
		// init
		var (
			cmd    *exec.Cmd
			output []byte
			err    error
		)

		// content
		for {
			cmd = exec.CommandContext(ctx, "go", "version")
			//cmd exec and get output
			if output, err = cmd.CombinedOutput(); err != nil {
				fmt.Println(err)
			}

			select {
			case <-cctx.Done():
				fmt.Println("done###" + string(output))
				goto TE
			default:
				fmt.Println("#######" + string(output))
			}
			time.Sleep(1 * time.Second)
		}
	TE:
		flag <- 1
		fmt.Println("sub end")
	}(ctx)

	time.Sleep(5 * time.Second)
	cancelF()
	<-flag
	fmt.Println("main end")
}
